import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/model/risemodel.dart';
import 'package:find_friend/pages/im/util/time.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_xspace.dart';
import 'package:find_friend/pages/xspace/detail/xdetailpage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 点赞列表
class MsgRaisePage extends StatefulWidget {
  @override
  _MsgRaisePageState createState() => _MsgRaisePageState();
}

class _MsgRaisePageState extends State<MsgRaisePage> {

  RefreshController _refreshController = RefreshController(initialRefresh: true);
  List<RiseModel> list = [];
  int page = 0;
  String myName = "";

  @override
  void initState() {
    super.initState();
    SharedUserInfo.instance().then((value) => setState(() => myName = value.nickname));
    _requstRead();
  }

  @override
  void dispose(){
    super.dispose();
    _refreshController.dispose();
  }

  _onRefresh() {
    page = 1;
    _request(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _request();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 5) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _request({bool isrefresh = false}) {
    var params = {"rows":5, "page":page, "upvotes": true};
    Networktool.request(API.upvoteme, params: params, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        Autogenerated model = Autogenerated.fromJson(data["data"]);
        _endNormoreData(model.data.length ?? 0);
        setState(() {
          if(isrefresh) list.clear();
          list.addAll(model.data);
        });
      }
    }
    ,finaly: _endrefres
    );
  }

  // 已读
  _requstRead() {
    Networktool.request(API.readupvote, method: NETWORKHTTPMethod.POST, success: (data){
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text("收到的赞"),
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: CustomRefreshWidget(
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        controller: _refreshController,
        child: ListView.builder(
          itemCount: list.length,
          itemBuilder: (context, index){
          return InkWell(
            onTap: (){
              // Navigator.push(context, CupertinoPageRoute(
              //   builder: (context) => XDetailPage(model: list[index].articleModel)
              // ));
              push(context, XDetailPage(model: list[index].articleModel));
            },
            child: _MsgReceiveCommentCell(model: list[index], ownername: myName,)
          );
        }),
      ),
    );
  }
}

class _MsgReceiveCommentCell extends StatelessWidget {
  final String ownername;
  final RiseModel model;

  const _MsgReceiveCommentCell({Key key, this.model, this.ownername}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;

    return Container(
      margin: const EdgeInsets.only(top: 5,left: 10, right: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8)
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left:10.0, top: 5, right: 19.5),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CustomCircleAvatar(size: 36.h, url: model.avatar,),
                SizedBox(width: 5,),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 5,),
                      Text("@${model.username}赞了你的${model.isreply ? '评论':'帖子'}", style: instanceTextStyle(13, APP_font_black),),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top:8.0),
                  child: Text(TimeUtil.convertTime(model.createtime * 1000), style: instanceTextStyle(9, APP_font_grey),),
                )
              ],
            ),
          ),
          Offstage(
            offstage: model.replyContent == null,
            child: Padding(
              padding: const EdgeInsets.only(left:50, bottom: 2),
              child: Text(model.replyContent ?? "", textAlign: TextAlign.left, style: instanceTextStyle(14, APP_font_black),),
            ),
          ),
          Offstage(
            offstage: model.replyVoice == null,
            child: Padding(
              padding: const EdgeInsets.only(left: 50),
              child: XspaceVoiceView(width: size.width * 0.4, voice: model.voice,),
            ),
          ),

          Offstage(
            offstage: model.replyPhoto == null,
            child: Padding(
              padding: const EdgeInsets.only(left: 50, top: 2),
              child: Text("[图片]", textAlign: TextAlign.left, style: instanceTextStyle(14, APP_font_black),),
            ),
          ),

          // 帖子
          Container(
            margin: const EdgeInsets.only(left: 50, right: 20, bottom: 12.5, top: 13),
            padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
            decoration: BoxDecoration(
              color: APP_scaffold_back_color,
              borderRadius: BorderRadius.circular(10)
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Offstage(
                  offstage: model.articlePhoto == null,
                  child: Container(
                    width: 80.h,
                    height: 80.h,
                    alignment: Alignment.center,
                    child: Stack(
                      children: [
                        PhysicalModel(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10),
                          clipBehavior: Clip.antiAlias,
                          child: Image.network(model.articlePhoto?.first?.url ?? "", width: 80.h, height: 80.h, fit: BoxFit.cover,),
                        ),
                        Offstage(
                          offstage: model.articlePhoto?.first?.ownerUrl == null,
                          child: Center(child: Image.asset("assets/huatingg.png",))
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(width: 10,),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "@${ownername ?? ''}", 
                        style: instanceTextStyle(13, APP_font_black),
                        maxLines: 1, overflow: TextOverflow.ellipsis,),
                      SizedBox(height: 9.5,),
                      Offstage(
                        // 只有语音不为空.发表内容为空的时候,这个文本才隐藏
                        offstage: (model.articleVoice != null && model.articleContent == null),
                        child: Text(
                          model.articleContent ?? "分享图片",
                          maxLines:3,
                          overflow: TextOverflow.ellipsis,
                          style: instanceTextStyle(11, APP_font_grey),
                        ),
                      ),
                      Offstage(
                        offstage: model.articleVoice == null,
                        child: IgnorePointer(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 0, top: 10),
                            child: XspaceVoiceView(width: size.width * 0.4, voice: model.articleVoice,),
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}